import openai
from flask import request
from flask_restful import Resource
from util import chatbot
import asyncio


async def fetch_url(uid, content, isGpt_4):
    for _ in range(32):
        try:
            loop = asyncio.get_event_loop()
            return await loop.run_in_executor(None, chatbot.ask, uid, content, chatbot.chat_log, isGpt_4)
        except openai.error.RateLimitError as e:
            print("一分钟之内只能请求三次，请稍后再试", "等待3秒")
            await asyncio.sleep(3)
            continue
        except openai.error.InvalidRequestError as e:
            print("上下文字数超出限制，请重置", "等待3秒")
            await asyncio.sleep(3)
            chatbot.reset_chat_log(chatbot.chat_log, uid)
            continue
        except Exception as e:
            print("其他异常", f"{str(e)}")
            # await asyncio.sleep(3)
            continue
    return None


async def requests_urls(urls):
    tasks = [fetch_url(url["uid"], url["content"][-11000:], False) for url in urls]
    return await asyncio.gather(*tasks)


# 汇言聚合请求
class chatAggregation(Resource):
    def post(self):
        urls: list = request.json['urls']

        results = asyncio.run(requests_urls(urls))
        res = []
        for i, result in enumerate(results):
            if result is not None:
                res.append({
                    "status": 200,
                    "data": result,
                    "id": urls[i]["id"]
                })
            else:
                res.append({
                    "status": 400,
                    "msg": "Failed to retrieve data from after 32 retries.",
                    "id": urls[i]["id"]
                })
        return res
